package Dao;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;

import pojo.Chess;
import pojo.Game;
import pojo.User;

public class GameDao {
	//属性
	private File file = new File("game.json");
	private ObjectMapper om = new ObjectMapper();
	//单例模式
	private static GameDao gameDao = new GameDao();
	private GameDao() {}
	public static GameDao getInstance() {
		return gameDao;
	}
	
	//add
	public boolean add(Game game) {
		ArrayList<Game> games = new ArrayList<>();
		
		try {
			games = this.om.readValue(file, new TypeReference<List<Game>>() {});
			games.add(game);
			om.writeValue(file, games);
			return true;
		}catch(MismatchedInputException e) {
			games.add(game);
			try {
				om.writeValue(file, games);
			} catch (IOException e1) {
				e1.printStackTrace();
				return false;
			}
			return true;
		}catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public boolean cover(Game game) {//更新winner
		ArrayList<Game> games = null;
		
		try {
			games = this.om.readValue(file, new TypeReference<List<Game>>() {});
			
			for(int i=0;i<games.size();i++) {
				if(games.get(i).getJia().equals(game.getJia())&&
				games.get(i).getYi().equals(game.getYi())&&
				games.get(i).getJia_win() == null){
					games.set(i, game);
					break;
				}
			}
			om.writeValue(file, games);
			return true;
		}
//		catch(MismatchedInputException e) {
//			games = new ArrayList<>();
//			games.add(game);
//			return false;
//		}
		catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public Game update(Game game,Chess chess) {//保存时候用
		ArrayList<Game> games = new ArrayList<>();
		
		try {
			int i=0;
			games = this.om.readValue(file, new TypeReference<List<Game>>() {});
			
			for(i=0;i<games.size();i++) {
				if(games.get(i).getJia().equals(game.getJia())&&
						games.get(i).getYi().equals(game.getYi())&&games.get(i).getJia_win() == null) {
					ArrayList<Chess> chesses = games.get(i).getChesses();
					chesses.add(chess);
					games.get(i).setChesses(chesses);
					games.get(i).setBlackNext(!games.get(i).isBlackNext());
					om.writeValue(file, games);
					return games.get(i);
				}
			}
		}catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public ArrayList<Game> list(){
		ArrayList<Game> games = null;
		
		try {
			games = this.om.readValue(file, new TypeReference<List<Game>>() {});
			return games;
		}catch(MismatchedInputException e) {
			return new ArrayList<>();
		}catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
